/**
 * Created by liuhe on 2017/5/18.
 * 模板数据入库执行脚本
 */
'use strict';

let mongoose = require('mongoose');
let fse = require('fs-extra');
let {allDBInfoConfig} = require('../config');
let TemplateInfoSchema = require('@qianmi/x-site-database/dao/templateInfo/template-info-schema').default;
mongoose.Promise = global.Promise;
(async () => {
    let args = process.argv.slice(2);
    let [envCode, filePath] = args;
    if(!envCode || !filePath){
        throw new Error('入参有误');
    }
    let list;
    if (envCode !== "test") {
        list = allDBInfoConfig.prod;
    } else {
        list = allDBInfoConfig.test;
    }
    
    try {
        let result = [];
        for (let i = 0, len = list.length; i < len; i++) {
            let envInfo= list[i];
            log(`开始部署${envInfo.label}环境模板================>`);
            result.concat(await upsetTemplateInfo(envInfo, filePath, envCode));
        }
        log(`全部更新完毕`);
        process.exit(0);
    } catch (e) {
        log(`更新出错`);
        throw e;
        // process.exit(e);
    }
    
    process.on('exit', function () {
        return 1;
    });
    
    process.on('uncaughtException', function (err) {
        log(err.stack);
        return 0;
    });
})();

async function upsetTemplateInfo(dbInfo, filePath, envCode) {
    let tplConfExists = fse.existsSync(filePath);
    let templateConfig = [];
    if (tplConfExists) {
        templateConfig = fse.readJsonSync(filePath);
    } else {
        throw new Error("模板入库信息不存在");
    }
    let {uri, dbName, options} = dbInfo;
    return await new Promise((resolve, reject) => {
        let db = mongoose.createConnection(uri + '/' + dbName, options);
        let modelName = `${envCode}_TemplateInfo`;
        let TemplateInfoModel = db.model(modelName, TemplateInfoSchema);
        db.once('open', () => {
            try {
                let result = upsetTemplateInfo2DB(TemplateInfoModel, templateConfig);
                resolve(result);
            } catch (e) {
                reject(e)
            }
        });
    });
}


async function upsetTemplateInfo2DB(TemplateInfoModel,templateConfig) {
    log(`有${templateConfig.length}条模板需要更新`);
    let result=[];
    for (let i = 0, len = templateConfig.length; i < len; i++) {
        let templateInfo = templateConfig[i];
        let conditions = {templateCode: templateInfo.templateCode};
        let options = {upsert: true};
        delete templateInfo._id;
        if(!templateInfo.updateTime){
            templateInfo.updateTime = "2016/1/1";
        }
        try {
            result.push(await new Promise((res, rej) => {
                TemplateInfoModel.update(conditions, templateInfo, options).exec((err, data) => {
                    err ? rej(err) : res(data);
                });
            }));
            log(`${i+1}  ${templateInfo.templateCode} 更新成功`);
        } catch (e) {
            log(`--->${i+1}  ${templateInfo.templateCode} 更新失败`);
            result.push(e);
        }
    }
    return result;
}

function log(str) {
    process.stdout.write(str + '\n');
}
